//
//  GaoFileManager.m
//  GaoPreviewDemo
//
//  Created by Gikki Ares on 2020/9/3.
//

#import "JsFileManager.h"

@implementation JsFileManager
//  /private/var/mobile/Containers/Shared/AppGroup/76D613E6-8B99-47EC-8FE9-7B21C69FBEE6/Documents/test.mov
//file:/var/mobile/Containers/Data/Application/4B6FC792-A7DB-4BCF-B362-97882EFA2A9D/Documents/tmp.mov
+ (NSString *)pathStringForFileInAppGroupNamed:(NSString *)appGroupName fileName:(NSString *)fileName {
	NSURL * url_appGroupSharedDir = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroupName];
	
	if([JsFileManager isFileExist:url_appGroupSharedDir.path]) {
		NSLog(@"File exist.");
	}
	else {
		NSLog(@"File is not exist.");
	}
	
	
	NSURL * url_filePath = [url_appGroupSharedDir URLByAppendingPathComponent:fileName];
	
	return [NSString stringWithFormat:@"%@",url_filePath.path];
}

//+ (NSString *)pathUrlForFileInAppGroupNamed:(NSString *)appGroupName fileName:(NSString *)fileName {
//	NSURL * url_appGroupSharedDir = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroupName];
//	
//	NSURL * url_filePath = [url_appGroupSharedDir URLByAppendingPathComponent:fileName];
//	
//	return url_filePath;
//}

///private/var/mobile/Containers/Shared/AppGroup/76D613E6-8B99-47EC-8FE9-7B21C69FBEE6/
//直接在共享目录下操作失败需要在Documents目录下
+ (NSURL *)urlForFileNamed:(NSString *)fileName inAppGroup:(NSString *)appGroup {
	NSURL * url_appGroupSharedDir = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroup];
	NSURL * url_fileDir = [url_appGroupSharedDir URLByAppendingPathComponent:@"Documents"];
	
	if([JsFileManager isFileExist:url_fileDir.path]) {
		NSLog(@"File exist.");
	}
	else {
		NSLog(@"File is not exist.");
		BOOL ret = [[NSFileManager defaultManager] createDirectoryAtPath:url_fileDir.path withIntermediateDirectories:YES attributes:nil error:nil];
		if(ret) {
			NSLog(@"Create file dir,success.");
		}
		else {
			NSLog(@"Create file dir,failed.");
		}
	}
	
	NSURL * url_filePath = [url_fileDir URLByAppendingPathComponent:fileName];
	
	return url_filePath;
}

+ (NSURL *)fileUrlOfFileInMainBundleNamed:(NSString *)strFileName {
	NSString *strPath = [[NSBundle mainBundle] pathForResource:strFileName ofType:nil];
	NSURL * urlFile = [NSURL fileURLWithPath:strPath];
	return urlFile;
}

+ (NSString *)pathStringForFileInDocumentDirectoryWithName:(NSString *)fileName {
	NSString * strFilePath = [NSString stringWithFormat:@"%@/%@",[self documentDirectory],fileName];
	return strFilePath;
}

+ (BOOL)isFileExist:(NSString *)filePath {
	return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}


+ (NSString *)documentDirectory {
	/*   缩略的url有可能找不到,还是用全称比较好.
	 $2,代表是否是扩展的名称.
	YES:扩展 /var/mobile/Containers/Data/Application/A9D13800-6096-4470-BE68-33D206A7AD56/Documents
	NO:缩略	 ~/Documents/record.mov
	*/
	 NSString * strPath_docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES).firstObject;
	return strPath_docDir;
}

+ (void)saveImageToAlbum:(UIImage *)image {
	UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

+ (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
	NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}


/*
 每天触发一次,保证日志文件的数量<=maxFileCount;
 int currentFileCount = N;
 如果大于了,删除日期最旧的后几个文件.所以要有一个文件控制类.
 */
+(void)keepFileCount:(int)count inDir:(NSString *)dirPath {
	NSFileManager * fm = [NSFileManager defaultManager];
		// 1 获取文件夹下的所有文件,创建file对象.
	NSArray *arrSubPath = [fm subpathsAtPath:dirPath];
	NSMutableArray * marr_file = [NSMutableArray new];
	[arrSubPath enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
			//去除扩展名
		NSString * strCreateDate = [obj stringByDeletingPathExtension];
		if(strCreateDate.length == 10) {
				//只处理名称符合规范的文件
			JsFile * file = [JsFile fileWithFilePath:[dirPath stringByAppendingPathComponent:obj]];
			[marr_file addObject:file];
//			NSLog(@"第%zi个文件,file path is %@",idx,file.filePath);
		}
	}];
	
	if(marr_file.count<=count) {
		return;
	}
	else {
			//日期小的放后面
		NSArray * sortedArray = [marr_file sortedArrayUsingComparator:^NSComparisonResult(JsFile *  _Nonnull file1, JsFile *  _Nonnull file2) {
			NSDate * date1 = file1.createdDate;
			NSDate * date2 = file2.createdDate;
			NSComparisonResult result = [date1 compare:date2];
			if(result == NSOrderedAscending) {
					//日期小的放后面.
				return NSOrderedDescending;
			}
			else {
				return NSOrderedAscending;
			}
		}];
			//删除后面的几个元素;
		NSInteger totalCount = sortedArray.count;
		NSInteger deleteCount = totalCount - count;
		NSLog(@"文件总数:%zi,最大文件数:%d,需要删除文件数:%zi",totalCount,count,deleteCount);
		for(int i = 0;i<deleteCount;i++) {
			NSInteger deleteIndex = totalCount-i-1;
			JsFile * file = sortedArray[deleteIndex];
			[file remove];
		}
	}
}

+ (NSArray *)fileArrayInDir:(NSString *)dirPath {
	NSFileManager * fm = [NSFileManager defaultManager];
		// 1 获取文件夹下的所有文件,创建file对象.
	NSArray *arrSubPath = [fm subpathsAtPath:dirPath];
	NSMutableArray * marr_file = [NSMutableArray new];
	[arrSubPath enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
		//只处理名称符合规范的文件
		JsFile * file = [JsFile fileWithFilePath:[dirPath stringByAppendingPathComponent:obj]];
		[marr_file addObject:file];
	}];
	return marr_file;
}

#pragma mark 1.2 清空
+ (void)emptyDir:(NSString *)dirPath {
	NSError * error = nil;
	[[NSFileManager defaultManager] removeItemAtPath:dirPath error:&error];
	if(error) {
		//may be dir is not exist.
//		NSLog(@"JsFileManager,remove file failed:%@,err:%@",dirPath,error.description);
	}
	[[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
}
+ (void)emptyFile:(NSString *)filePath {
	[[NSData data] writeToFile:filePath atomically:YES];
}

@end
